package com.cenjiawen.common;

import java.net.URI;
import java.net.URISyntaxException;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.plugin.redis.RedisPlugin;
import com.utils.PathUtils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

public class WSUtils {
	public static void main(String[] args) {
		new WSUtils().ws();
	}

	private FileWriter fileWriter = new FileWriter(PathUtils.getFile("logs", "smslog.txt"));
	private FileWriter body = new FileWriter(PathUtils.getFile("logs", "smsbodylog.txt"));
	private FileWriter statusinfo = new FileWriter(PathUtils.getFile("logs", "smsstatusinfolog.txt"));
	WebSocketClient mWs;

	public void cnt() {
		try {
			mWs = init();
			mWs.connect();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
	}

	public WebSocketClient init() throws URISyntaxException {
		URI uri = new URI(url);
		Cache cache = Redis.use();
		return new WebSocketClient(uri) {
			@Override
			public void onOpen(ServerHandshake serverHandshake) {
				System.out.println("onOpen");
			}

			@Override
			public void onMessage(String s) {
				System.out.println("onMessage: " + s);
				body.append(DateUtil.now() + "\n");
				body.append(s + "\n");
				JSONArray array = JSONUtil.parseArray(s);
				JSONObject jsonObject = JSONUtil.parseObj(array.toArray()[0]);
				// JSONObject jsonObject = JSONUtil.parseObj(s);
				String event = jsonObject.getStr("event");
				if (!"preferredService".equals(event)) {
					return;
				}
				String recipHashID = jsonObject.getStr("recipHashID");
				int prefServ = jsonObject.getInt("prefServ");
				statusinfo.append(recipHashID + " " + (prefServ == 1 ? "成功" : "失败") + "\n");
				if (cache.get(recipHashID) != null) {
					return;
				}
				if (prefServ == 1) {
					cache.setex(recipHashID, 10000, recipHashID);
					fileWriter.append(recipHashID + " 成功\n");
				}
			}

			@Override
			public void onClose(int i, String s, boolean b) {
				System.out.println("onClose");
				cnt();
			}

			@Override
			public void onError(Exception e) {
				System.out.println("onError");
				e.printStackTrace();
				cnt();
			}
		};
	}

	String url = "ws://192.168.199.245:333/service";

	public WSUtils() {
		try {
			RedisPlugin rp = new RedisPlugin("myRedis", "localhost");
			// 与web下唯一区别是需要这里调用一次start()方法
			rp.start();
			Cache cache = Redis.use();
			// ws://192.168.199.245:333/service
			// 这里用的binance的socket接口，国内调用需要VPN，使用换成你的就行
			// String url = "wss://stream.binance.com:9443/ws/ethbtc@ticker";
			// String url = "wss://stream.binance.com:9443/ws/ethbtc@depth20";
			cnt();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void ws() {
	}
}
